<template>
  <div class="line-chart-container">
    <div v-if="loading" class="chart-loading">
      <i class="el-icon-loading"></i>
      <span>数据加载中...</span>
    </div>
    <div ref="lineChart" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import moment from 'moment';
import { sseManager } from '@/api/tool/sse-manager.js';
import { throttle } from 'lodash-es';

// 常量配置
const COLOR_LIST = ['#5470c6', '#91cc75']; // 主色/平均值颜色
const AREA_STYLE = {
  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: 'rgba(84,112,198,0.6)' },
    { offset: 1, color: 'rgba(84,112,198,0.05)' }
  ])
};

export default {
  name: "SalesLineChart",
  data() {
    return {
      chartInstance: null,
      unsubscribe: null,
      loading: true,
      option: {
        title: {
          text: '销售额实时监控',
          left: 'center',
          textStyle: {
            fontSize: 18,
            color: '#2c3e50'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderWidth: 0,
          formatter: params => {
            //console.log('tooltip 参数:', params); // 调试输出
            if (!params || !params.length) return '';
            const value = params[0].value;
            const timestamp = params[0].data?.timestamp ? moment(params[0].data.timestamp).format('HH:mm:ss') : 'N/A';
            return `
              <div style="margin:5px">
                ${params[0].axisValue}<br/>
                <span style="display:inline-block;width:10px;height:10px;background:${COLOR_LIST[0]};border-radius:50%"></span>
                销售额：${this.formatYAxis(value)}<br/>
                <span style="color:#999">更新时间：${timestamp}</span>
              </div>
            `;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          top: '15%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: { lineStyle: { color: '#ccc' } },
          data: ['Q1', 'Q2', 'Q3', 'Q4']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => this.formatYAxis(value)
          },
          splitLine: {
            lineStyle: { type: 'dashed' }
          }
        },
        series: [{
          name: '销售额',
          type: 'line',
          data: [],
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 3 },
          areaStyle: AREA_STYLE,
          itemStyle: { color: COLOR_LIST[0] },
          markLine: {
            silent: true,
            symbol: 'none',
            lineStyle: { color: COLOR_LIST[1], type: 'solid' },
            label: { color: '#666' },
            itemStyle: {color: '#ff0000' // 🎨 这里修改箭头颜色，比如红色
            },
            data: [{ type: 'average', name: '平均值' }]
          }
        }]
      }
    };
  },
  mounted() {
    this.initChart();
    this.subscribeData();

    // 手动注入测试数据用于验证
    this.updateChart({ Q1: 420, Q2: 548, Q3: 222, Q4: 309, timestamp: Date.now() });

    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    /** 初始化图表 */
    initChart() {
      console.log('初始化图表');
      this.chartInstance = echarts.init(this.$refs.lineChart);
      console.log('图表实例:', this.chartInstance);
      this.chartInstance.setOption(this.option);
    },

    /** 订阅数据更新（500ms节流） */
    subscribeData() {
      const updateHandler = throttle(payload => {
        //console.log("接收到的数据 payload:", payload);

        this.loading = false;
        this.updateChart(payload);
      }, 500);

      this.unsubscribe = sseManager.subscribe('update', updateHandler);
    },

    /** 更新图表数据 */
    updateChart(payload) {
      if (!this.validateData(payload)) {
        console.warn('数据校验失败:', payload);
        return;
      }

      const seriesData = ['Q1', 'Q2', 'Q3', 'Q4'].map(key => ({
        value: payload[key],
        timestamp: payload.timestamp
      }));

      const newOption = {
        title: {
          text: `销售额监控 - ${moment(payload.timestamp).format('MM月DD日')}`,
          left: 'center',
          top: '5%', // 可选：控制标题距离顶部位置
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.8)',
          borderWidth: 0,
          formatter: params => {
            //console.log('tooltip 参数:', params); // 调试输出
            if (!params || !params.length) return '';
            const value = params[0].value;
            const timestamp = params[0].data?.timestamp ? moment(params[0].data.timestamp).format('HH:mm:ss') : 'N/A';
            return `
              <div style="margin:5px">
                ${params[0].axisValue}<br/>
                <span style="display:inline-block;width:10px;height:10px;background:${COLOR_LIST[0]};border-radius:50%"></span>
                销售额：${this.formatYAxis(value)}<br/>
                <span style="color:#999">更新时间：${timestamp}</span>
              </div>
            `;
          }
        },
        grid: {
          left: '8%',
          right: '5%', // 增加右边距，防止 markLine 被截断
          top: '15%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: { lineStyle: { color: '#ccc' } },
          data: ['Q1', 'Q2', 'Q3', 'Q4']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: (value) => this.formatYAxis(value)
          },
          splitLine: {
            lineStyle: { type: 'dashed' }
          }
        },
        series: [{
          name: '销售额',
          type: 'line',
          data: seriesData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: { width: 3 },
          areaStyle: AREA_STYLE,
          itemStyle: { color: COLOR_LIST[0] },
          markLine: {
            silent: true,
            symbol: ['none', 'arrow'], // 左侧无箭头，右侧有箭头
            symbolSize: [8, 12], // 设置箭头大小 [宽度, 高度]
            lineStyle: { color: COLOR_LIST[1], type: 'solid' },
            label: { color: '#666' },
            itemStyle: {color: '#ff0000' // 🎨 这里修改箭头颜色，比如红色
            },
            data: [{
              type: 'average',
              value: this.calculateAverage(seriesData)
            }]
          }
        }]
      };

      if (!this.chartInstance) {
        console.error('图表实例未初始化');
        return;
      }

      this.chartInstance.setOption(newOption, true);
    },

    /** 数据校验 */
    validateData(payload) {
      const requiredKeys = ['Q1', 'Q2', 'Q3', 'Q4', 'timestamp'];
      return requiredKeys.every(k =>
        typeof payload[k] !== 'undefined' &&
        payload[k] !== null &&
        !isNaN(Number(payload[k])) &&
        moment(payload.timestamp).isValid()
      );
    },

    /** 计算动态平均值 */
    calculateAverage(data) {
      const sum = data.reduce((acc, cur) => acc + cur.value, 0);
      return sum / data.length;
    },

    /** Y轴格式化（增强容错） */
    formatYAxis(value) {
      const num = Number(value);
      if (isNaN(num)) {
        console.warn('formatYAxis 接收到非数字值:', value);
        return '0元';
      }
      if (num >= 1e8) return `${(num / 1e8).toFixed(1)}亿`;
      if (num >= 1e4) return `${Math.floor(num / 1e4)}万`;
      return `${num.toLocaleString()}元`;
    },

    /** 响应式调整 */
    resizeChart() {
      console.log('调整图表尺寸');
      this.chartInstance?.resize();
    },

    /** 资源清理 */
    cleanup() {
      this.unsubscribe?.();
      this.chartInstance?.dispose();
      window.removeEventListener('resize', this.resizeChart);
    }
  }
};
</script>

<style scoped>
.line-chart-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  /*box-shadow: 0 2px 12px rgba(0,0,0,0.1);*/
}

.chart-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;

  .el-icon-loading {
    margin-right: 8px;
    font-size: 18px;
  }
}
</style>